<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Member extends Admin_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('credit_m');
        $this->config->load('userset');
        $this->load->library('pagination');
        $this->load->library('mekey');
        $this->load->model('member_m');
        $this->load->model('moneysale_m');
        $this->load->model('moneystage_m');
    }

    public function index($page = 1)
    {
        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/index/');
        $config['total_rows']       = $this->db->where("user_group<", 3)->count_all('users');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $data['users']      = $this->user_m->get_user_group_rule_list($start, $limit);
        // pp($data);exit();
        $this->load->view('member/index', $data);
    }

    public function add()
    {
        $usergroup         = $this->authGroup_m->get_all_groups(1);
        $data['usergroup'] = $usergroup;
        $this->load->view('member/form', $data);
    }

    public function edit($uid)
    {
        if ($uid) {
            $member = $this->user_m->get_user_by_user_id_group($uid);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/index'), 1);
        }
        $usergroup         = $this->authGroup_m->get_all_groups(1);
        $data['usergroup'] = $usergroup;
        $data['member']    = $member;
//        pp($data);exit();
        $this->load->view('member/form', $data);
    }

    public function update()
    {
        $post     = $this->input->post();
        $uid      = isset($post['user_id']) ? intval($post['user_id']) : false;
        $username = isset($post['user']) ? htmlspecialchars($post['user'], ENT_QUOTES) : '';
        $group_id = isset($post['user_group']) ? intval($post['user_group']) : false;
        if (!$group_id) {
            show_message('请给用户选择用户组', site_url(X_URL . 'member/add'), 1);
        }
        $salt        = get_salt();
        $getpassword = $this->input->post('user_password', true);
        if (!$uid) {
            $admin = [
                'user_name'     => $username,
                'user_password' => password_dohash($getpassword, $salt),
                'user_salt'     => $salt,
                'user_credit'   => $this->config->item('credit_start'),
                'user_regip'    => get_onlineip(),
                'user_money'    => 0,
                'user_group'    => $group_id,
                'user_regtime'  => time(),
                'user_logtime'  => time(),
                'user_lock'     => 0,
                'user_sex'      => $post['user_sex'],
                'user_tel'      => $post['user_tel'],
                'user_qq'       => $post['user_qq'],
                'user_email'    => $post['user_email'],
            ];

            if (!$this->user_m->check_register_username($username)) {
                $this->user_m->register($admin);
                $new_id = $this->db->insert_id();
                // 注册送100积分
                $credit = [
                    "user_id"     => $new_id,
                    "credit_num"  => $this->config->item('credit_start'),
                    "credit_type" => 0,
                    "credit_time" => time(),
                ];
                $this->credit_m->add_fox_credits($credit);
            }

            $this->user_m->update_user($new_id, ['user_key' => password_dohash($new_id, $salt)]);
            $this->groupAcess_m->insert_user_access(['uid' => $new_id, 'group_id' => $group_id]);
            show_message('新增用户成功', site_url(X_URL . 'member/index'), 1);
        } else {
            // 修改
            $admin = [
                'user_group' => $group_id,
                'user_sex'   => $post['user_sex'],
                'user_tel'   => $post['user_tel'],
                'user_qq'    => $post['user_qq'],
                'user_email' => $post['user_email'],
            ];
            if (!empty($getpassword)) {
                $admin['user_salt']     = $salt;
                $admin['user_password'] = password_dohash($getpassword, $salt);
            }
            if (!empty($username)) {
                $admin['user_name'] = $username;
            }
            $this->user_m->update_user($uid, $admin);
            $this->groupAcess_m->update_user_access($uid, ['group_id' => $group_id]);
            show_message('修改用户成功', site_url(X_URL . 'member/index'), 1);
        }
    }

    //用户搜索
    public function search($title = '', $page = 1)
    {

        // $start = ($page-1)*$limit;
        $keywords = !empty($title) ? $this->mekey->base_decode($title) : $this->input->post('user_name');
        if (!$keywords) {
            exit;
            // echo json_encode(array('status' => '4','msg' => '抱歉，您没有输入搜索词'));
        }
        if (!get_words_tags_arr($keywords)) {
            $sokey = explode(" ", $keywords);
        } else {
            $sokey = !empty($title) ? get_words_tags_arr($this->mekey->base_decode($title)) : get_words_tags_arr($keywords);
        }
        $sekey = $this->mekey->base_encode($keywords);
        //分页
        $limit                      = 20;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['total_rows']       = $this->user_m->count_user_find($sokey);
        $config['base_url']         = site_url('manage/member/search/');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $start                      = ($page - 1) * $limit;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        // $total = $this->user_m->count_user_find($sokey);
        $users = $this->user_m->user_find($start, $limit, $sokey);
        if ($users) {
            foreach ($sokey as $s => $m) {
                foreach ($users as $k => $v) {
                    $users[$k]['user_name'] = str_replace($m, '<cite class="text-red">' . $m . '</cite>', $v['user_name']);
                }
            }
        }

        $data['users'] = $users;
        // pp($data);exit;
        $this->load->view('member/index', $data);
    }

    public function users($page = 1)
    {
        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/users/');
        $config['total_rows']       = $this->db->where("user_group>", 2)->count_all('users');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $users              = $this->user_m->get_users_list($start, $limit);
//        if(!empty($users)){
//            foreach ($users as $key => $val){
//                $users[$key]['avatar'] = $this->upload_m->get_avatar_url($this->session->userdata('user_id'), 'small');
//            }
//        }
        $data['users'] = $users;
//        pp($data);exit();
        $this->load->view('member/users', $data);
    }

    public function frozen($user_id, $status)
    {
        if (!$user_id) {
            return false;
        }
        $info = $this->user_m->get_user_by_user_id($user_id);
        if (!empty($info)) {
            if ($status == 1) {
                // 冻结
                $return = $this->user_m->update_user($user_id, ['user_lock' => 1]);
            }
            if ($status == 2) {
                // 解冻
                $return = $this->user_m->update_user($user_id, ['user_lock' => 0]);
            }
            if ($return) {
                show_message('冻结用户成功', site_url(X_URL . 'member/users'), 1);
            } else {
                show_message('冻结用户失败', site_url(X_URL . 'member/users'), 1);
            }
        }
    }

    public function edit_user($uid)
    {
        if ($uid) {
            $member = $this->user_m->get_user_by_user_id($uid);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
        $data['member'] = $member;
//        pp($data);exit();
        $this->load->view('member/user_form', $data);
    }

    public function update_user()
    {
        $cur_uid                 = $this->session->userdata('user_id');
        $post                    = $this->input->post();
        $uid                     = isset($post['user_id']) ? intval($post['user_id']) : false;
        $data['user_money_real'] = isset($post['user_money_real']) ? $post['user_money_real'] : '0';
        $return                  = $this->user_m->update_user($uid, $data);
        if ($return) {
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "修改用户" . $uid . "的销售贷额度");
            show_message('修改用户成功', site_url(X_URL . 'member/users'), 1);
        } else {
            show_message('修改用户失败', site_url(X_URL . 'member/users'), 1);
        }
    }

    public function rz_user($uid = 0)
    {

        if ($uid) {
            $member      = $this->user_m->get_user_by_user_id($uid);
            $data['uid'] = $uid;
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
        // 认证图片
        if ($member['user_card_rz'] > 0) {
            $pic_path         = "[";
            $pic_path         .= "'" . base_url('uploads/card/' . $uid . '/a_pic.jpg?t=' . time()) . "',";
            $pic_path         .= "'" . base_url('uploads/card/' . $uid . '/b_pic.jpg?t=' . time()) . "',";
            $pic_path         .= "'" . base_url('uploads/card/' . $uid . '/c_pic.jpg?t=' . time()) . "',";
            $pic_path         .= "'" . base_url('uploads/card/' . $uid . '/d_pic.jpg?t=' . time()) . "',";
            $pic_con[]        = [
                'caption' => "身份证正面照",
                'width'   => '120px',
                'url'     => "",
                "key"     => "4",
            ];
            $pic_con[]        = [
                'caption' => "身份证反面照",
                'width'   => '100px',
                'url'     => "",
                "key"     => "4",
            ];
            $pic_con[]        = [
                'caption' => "征信报告",
                'width'   => '100px',
                'url'     => "",
                "key"     => "4",
            ];
            $pic_con[]        = [
                'caption' => "公账流水",
                'width'   => '100px',
                'url'     => "",
                "key"     => "4",
            ];
            $data['pic_path'] = $pic_path . "]";
            $data['pic_con']  = json_encode($pic_con);
        } else {
            $data['pic_path'] = "[]";
            $data['pic_con']  = json_encode([]);
        }
        $data['member'] = $member;
        $this->load->view('member/rz_form', $data);
    }

    public function rz_user_action()
    {
        $cur_uid = $this->session->userdata('user_id');
        $get     = $this->input->get();
        $uid     = $get['uid'];
        $action  = $get['action'];
        $return  = $this->user_m->update_user($uid, ['user_card_rz' => $action]);
        if ($return) {
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "审核用户：" . $uid . "实名认证");
            echo json_encode(['code' => 200, 'msg' => '操作成功']);
            exit();
        } else {
            echo json_encode(['code' => 400, 'msg' => '操作失败，请稍后再试']);
            exit();
        }
    }

    /**
     * 设置额度
     */
    public function set_edu($uid)
    {

        if ($uid) {
            $member = $this->user_m->get_user_by_user_id($uid);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
        $data['member'] = $member;
//        pp($data);exit();
        $this->load->view('member/set_edu', $data);
    }

    public function set_edu_action()
    {
        $cur_uid    = $this->session->userdata('user_id');
        $get        = $this->input->get();
        $uid        = $get['uid'];
        $user_money = $get['user_money'];
        $member     = $this->user_m->get_user_by_user_id($uid);
        if ($member) {
            if ($member['user_money'] > 0) {
                $message_txt = '您的销售贷额度调整了！<br>您的销售贷额度：<b>' . $user_money;
            } else {
                $message_txt = '恭喜您，您的销售贷审核通过了！<br>您的销售贷额度：<b>' . $user_money . '</b>';
            }
            $add_num         = ($user_money * 100 - $member['user_money'] * 100) / 100;
            $user_money_real = $member['user_money_real'] + $add_num;
        }
        $return = $this->user_m->update_user($uid, ['user_money' => $user_money, 'user_money_real' => $user_money_real]);
        if ($return) {
            $massage = [
                'message_txt'    => $message_txt,
                'message_to_uid' => $uid,
                'message_time'   => date("Y-m-d H:i:s"),
            ];
            $this->message_m->add_massage($massage);
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "设置用户：" . $uid . "销售贷额度");
            echo json_encode(['code' => 200, 'msg' => '操作成功']);
            exit();
        } else {
            echo json_encode(['code' => 400, 'msg' => '操作失败，请稍后再试']);
            exit();
        }
    }

    public function set_load($uid)
    {

        if ($uid) {
            $member = $this->user_m->get_user_by_user_id($uid);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
        $data['member'] = $member;
//        pp($data);exit();
        $this->load->view('member/set_load', $data);
    }

    public function set_load_action()
    {
        $cur_uid = $this->session->userdata('user_id');
        $get     = $this->input->get();
        // pp($get);exit();
        $uid       = $get['uid'];
        $stage_num = $get['stage_num'];
        $return    = $this->user_m->update_user($uid, ['stage_num' => $stage_num]);
        if ($return) {
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "设置用户：" . $uid . "销售贷分期数：" . $stage_num);
            echo json_encode(['code' => 200, 'msg' => '操作成功']);
            exit();
        } else {
            echo json_encode(['code' => 400, 'msg' => '操作失败，请稍后再试']);
            exit();
        }
    }

    public function xiaoshoudai($uid, $page = 1)
    {
        if ($uid) {
            $member = $this->user_m->get_user_by_user_id($uid);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
        $this->load->model('moneysale_m');
        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/xiaoshoudai/' . $uid);
        $config['total_rows']       = $this->db->where("user_id", $uid)->count_all('user_money_sale');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $logs               = $this->moneysale_m->get_all_user_money_sale($start, $limit, $uid);
        $data['logs']       = $logs;
        $data['member']     = $member;
//        pp($data);exit();
        $this->load->view('member/sale_info', $data);
    }

    public function return_money()
    {
        $cur_uid  = $this->session->userdata('user_id');
        $get      = $this->input->get();
        $money_id = $get['return_id'];
        $this->load->model('moneysale_m');
        $this->load->model('moneylogs_m');
        $return = $this->moneysale_m->sava_user_money_sale($money_id, ['is_return' => 1]);
        if ($return) {
            // 余额回复，增加一条日志
            $money_sale_info = $this->moneysale_m->get_user_money_sale_by_id($money_id);
            if ($money_sale_info) {
                $this->db->set('user_money_real', 'user_money_real+' . $money_sale_info['order_cost'], false)->where('user_id', $money_sale_info['user_id'])->update('users');
                // 变动日志
                $money_log = [
                    'user_id'        => $money_sale_info['user_id'],
                    'user_money_num' => $money_sale_info['order_cost'],
                    'type'           => 2,
                    'remark'         => "销售贷还款",
                    'ctime'          => date("Y-m-d H:i:s"),
                ];
                $this->moneylogs_m->add_money_logs($money_log);
            }
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "确认用户：" . $money_sale_info['user_id'] . "还款销售贷");
            echo json_encode(['code' => 200, 'msg' => '操作成功']);
            exit();
        } else {
            echo json_encode(['code' => 400, 'msg' => '操作失败，请稍后再试']);
            exit();
        }
    }

    public function money_stage($sale_id)
    {

        if ($sale_id) {
            $sale_info          = $this->moneysale_m->get_user_money_sale_by_id($sale_id);
            $stage_link_id      = $sale_info['stage_link_id'];
            $link_info          = $this->moneystage_m->get_link_by_id($stage_link_id);
            $fenqi_str          = $link_info['money_stage'];
            $fenqi_arr          = explode(",", $fenqi_str);
            $loan_stage         = $this->moneystage_m->get_list_stage_by_fenqi_arr($fenqi_arr);
            $data['loan_stage'] = $loan_stage;
            $this->load->view('member/stage_info', $data);
        } else {
            show_message('参数错误', site_url(X_URL . 'member/users'), 1);
        }
    }

    public function return_money_fenqi()
    {
        $cur_uid  = $this->session->userdata('user_id');
        $get      = $this->input->get();
        $money_id = $get['return_id'];
        $this->load->model('moneysale_m');
        $this->load->model('moneylogs_m');
        $return = $this->moneystage_m->sava_user_stage($money_id, ['is_return' => 1]);
        if ($return) {
            // 余额回复，增加一条日志
            $money_stage_info = $this->moneystage_m->get_user_stage_by_id($money_id);
            if ($money_stage_info) {
                $user_info = $this->user_m->get_user_by_user_id($money_stage_info['user_id']);
                if ($user_info['user_money_real'] + $money_stage_info['real_stage_money'] > $user_info['user_money']) {
                    $this->db->set('user_money_real', $user_info['user_money'], false)->where('user_id', $money_stage_info['user_id'])->update('users');
                } else {
                    $this->db->set('user_money_real', 'user_money_real+' . $money_stage_info['real_stage_money'], false)->where('user_id', $money_stage_info['user_id'])->update('users');
                }
                // 变动日志
                $money_log = [
                    'user_id'        => $money_stage_info['user_id'],
                    'user_money_num' => $money_stage_info['real_stage_money'],
                    'type'           => 2,
                    'remark'         => "销售贷分期还款",
                    'ctime'          => date("Y-m-d H:i:s"),
                ];
                $this->moneylogs_m->add_money_logs($money_log);
            }
            $this->logs_m->add_logs($cur_uid, "管理ID：" . $cur_uid . "确认用户：" . $money_stage_info['user_id'] . "还款销售贷");
            echo json_encode(['code' => 200, 'msg' => '操作成功']);
            exit();
        } else {
            echo json_encode(['code' => 400, 'msg' => '操作失败，请稍后再试']);
            exit();
        }
    }

    public function xiaoshoudai_list($page = 1)
    {
        $this->load->model('moneysale_m');
        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/xiaoshoudai_list/');
        $config['total_rows']       = $this->db->where("is_return !=", 2)->count_all('user_money_sale');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $logs               = $this->moneysale_m->get_all_user_money_sale_list($start, $limit);
        $data['logs']       = $logs;
        $this->load->view('member/sale_info_list', $data);
    }

    //导出订单
    public function export_excel()
    {
        $this->load->model('moneysale_m');
        $endtime      = $this->input->get('endtime');
        $starttime    = $this->input->get('starttime');
        $end          = $endtime . " 23:59:59";
        $start        = $starttime . "  00:00:00";
        $list         = $this->moneysale_m->get_all_user_money_sale_list_by_time($end, $start);
        $export_excel = [];
        if ($list) {
            foreach ($list as $k => $v) {
                $export_excel[$k]['ctime']          = $v['ctime'];
                $export_excel[$k]['user_name']      = $v['user_name'];
                $export_excel[$k]['order_no']      = $v['order_no'];
                $export_excel[$k]['order_cost']     = $v['order_cost'];
                $export_excel[$k]['stage_num']      = $v['stage_num'] ?? 3;
            }
        }
        // pp($export_excel);exit();
        $filename = '销售贷分期报表' . date('Ymd');
        $header   = ['下单时间', '用户名', '订单号', '分期总金额', '分期数'];
        $index    = ['ctime', 'user_name', 'order_no', 'order_cost', 'stage_num'];
        $this->createtable($export_excel, $filename, $header, $index);
    }

    protected function createtable($list, $filename, $header = [], $index = [])
    {
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=" . $filename . ".xls");
        header("Expires: 0");
        header("Pragma: public");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        $teble_header = implode("\t", $header);
        $strexport    = $teble_header . "\r";
        foreach ($list as $row) {
            foreach ($index as $val) {
                $strexport .= $row[$val] . "\t";
            }
            $strexport .= "\r";
        }
        $strexport = iconv('UTF-8', "GB2312//IGNORE", $strexport);

        exit($strexport);
    }

    public function money_stage_list($page = 1)
    {

        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/money_stage_list/');
        $config['total_rows']       = $this->db->count_all('user_stage');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $loan_stage         = $this->moneystage_m->get_all_user_stage_list($start, $limit);
        if (!empty($loan_stage)) {
            foreach ($loan_stage as $key => $val) {
                $user_info                     = $this->user_m->get_user_by_user_id($val['user_id']);
                $loan_stage[$key]['user_name'] = $user_info['user_name'];
            }
        }
        $data['loan_stage'] = $loan_stage;
        $this->load->view('member/stage_info_list', $data);
    }

    public function recommend_list($page = 1)
    {
        $this->load->model('recommend_m');
        $limit                      = 30;
        $config['uri_segment']      = 4;
        $config['use_page_numbers'] = true;
        $config['base_url']         = site_url('manage/member/recommend_list/');
        $config['total_rows']       = $this->db->count_all('recommend');
        $config['per_page']         = $limit;
        $config['num_links']        = 10;
        $this->pagination->initialize($config);
        $start              = ($page - 1) * $limit;
        $data['pagination'] = $this->pagination->create_links();
        $recommend          = $this->recommend_m->get_all_recommend($start, $limit);
        if (!empty($recommend)) {
            foreach ($recommend as $key => $val) {
                $user_info                    = $this->user_m->get_user_by_user_id($val['user_id']);
                $recommend[$key]['user_name'] = $user_info['user_name'];
            }
        }
        $data['recommend'] = $recommend;
        $this->load->view('member/recommend_list', $data);
    }
}
